package EP1.main;

import java.util.ArrayList;

public class CoreNumberFinder {

    public static void main(String[] args) {
	System.out.println("cores: " + findCoreNumber());
    }

    public static int findCoreNumber() {
	double gainFactor = 0;
	int cores = 0;
	ArrayList<Thread> threadList = new ArrayList<Thread>();
	int forsize = 300000;
	int[] matrix = new int[forsize];
	long begin, end = 0, deltaOld = Long.MAX_VALUE, deltaNew;

	do {
	    threadList.clear();

	    begin = System.currentTimeMillis();

	    for (int i = 0; i <= cores; i++) {
		threadList.add(new Thread(new SimpleTest(cores + 1, matrix)));
	    }

	    for (Thread t : threadList) {
		t.start();
	    }

	    for (Thread t : threadList) {
		try {
		    t.join();
		} catch (InterruptedException e) {
		    e.printStackTrace();
		}
	    }

	    end = System.currentTimeMillis();

	    deltaNew = end - begin;

	    if (deltaNew > 0) {
		gainFactor = (double) deltaOld / deltaNew;

//		System.out.println("delta_old: " + deltaOld);
//		System.out.println("delta_new: " + deltaNew);
//		System.out.println("ganho: " + gainFactor);
//		System.out.println();

		if (gainFactor > 1)
		    cores++;

		deltaOld = deltaNew;
	    } else {
//		System.out.println("delta_new pequeno demais");
		if (deltaNew <= deltaOld) {
		    forsize *= 5;
		    matrix = new int[forsize];
		    gainFactor = 2;
		    if (deltaNew == 0) deltaNew = 1;
		    deltaOld = 5 * deltaNew;
		}
		else {
		    break;
		}
	    }

	} while (gainFactor > 1);

	return cores;
    }
}
